<template>
  <div class="user-bg">
    <div class="profile-container">
      <!-- 顶部用户信息卡片 -->
      <div class="profile-header" :class="{ 'loading': loading }">
        <div class="avatar-section">
          <div class="avatar-wrapper">
            <el-avatar
              :size="80"
              :src="userStore.avatar"
              class="avatar"
            >
              <el-icon><User /></el-icon>
            </el-avatar>
            <div class="avatar-edit">
              <el-icon><Camera /></el-icon>
            </div>
          </div>
          <div class="user-info">
            <h2 class="username">{{ userStore.nickname || '用户' }}</h2>
            <p class="user-id">ID: {{ profileData.id || '--' }}</p>
            <p v-if="userStore.isThirdParty" class="login-type">钉钉登录</p>
          </div>
        </div>
      </div>

      <!-- 用户快速统计信息 -->
      <div class="user-quick-stats">
        <div class="stat-item">
          <div class="stat-value">{{ myStats.posts }}</div>
          <div class="stat-label">动态</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ myStats.favorites }}</div>
          <div class="stat-label">收藏</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ myStats.likes }}</div>
          <div class="stat-label">点赞</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ myStats.fans }}</div>
          <div class="stat-label">粉丝</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ myStats.follows }}</div>
          <div class="stat-label">关注</div>
        </div>
      </div>

      <!-- 个人信息卡片 -->
      <div class="profile-card" :class="{ 'loading': loading }">
        <div class="card-header">
          <h3>个人信息</h3>
          <template v-if="!editing && !isGuest">
            <el-button type="primary" size="small" text @click="editing = true">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
          </template>
          <template v-else-if="editing && !isGuest">
            <el-button type="primary" size="small" @click="saveProfile" :loading="saving">保存</el-button>
            <el-button size="small" @click="cancelEdit">取消</el-button>
          </template>
        </div>
        <div v-if="editing">
          <el-form :model="profileData" label-width="60px">
            <el-form-item label="性别">
              <el-select v-model="profileData.gender" placeholder="请选择">
                <el-option label="男" value="M" />
                <el-option label="女" value="F" />
              </el-select>
            </el-form-item>
            <el-form-item label="生日">
              <el-date-picker v-model="profileData.birthdate" type="date" placeholder="选择日期" />
            </el-form-item>
            <el-form-item label="身高">
              <el-input v-model="profileData.height" placeholder="请输入身高(cm)" type="number" min="0" />
            </el-form-item>
            <el-form-item label="体重">
              <el-input v-model="profileData.weight" placeholder="请输入体重(kg)" type="number" min="0" />
            </el-form-item>
          </el-form>
        </div>
        <div v-else class="info-grid">
          <div class="info-item" v-for="(item, index) in infoItems" :key="index">
            <div class="info-label">
              <el-icon><component :is="item.icon" /></el-icon>
              {{ item.label }}
            </div>
            <div class="info-value" :class="{ 'link': !!item.action }" @click="item.action ? item.action() : null">
              {{ item.value }}
              <el-icon v-if="item.action"><ArrowRight /></el-icon>
            </div>
          </div>
        </div>
      </div>

      <!-- 身体数据卡片 -->
      <div class="body-data-card" :class="{ 'loading': loading }">
        <div class="card-header">
          <h3>身体数据</h3>
        </div>

        <div class="data-grid">
          <div class="data-item">
            <div class="data-circle" :class="heightLevel">
              <div class="data-number">{{ profileData.height || '--' }}</div>
              <div class="data-unit">cm</div>
            </div>
            <div class="data-label" :class="heightLevel">身高</div>
          </div>

          <div class="data-item">
            <div class="data-circle" :class="weightLevel">
              <div class="data-number">{{ profileData.weight || '--' }}</div>
              <div class="data-unit">kg</div>
            </div>
            <div class="data-label" :class="weightLevel">体重</div>
          </div>

          <div class="data-item">
            <div class="data-circle" :class="bmiLevel">
              <div class="data-number">{{ bmiValue }}</div>
              <div class="data-unit">BMI</div>
            </div>
            <div class="data-label" :class="bmiLevel">体质指数</div>
          </div>

          <div class="data-item">
            <div class="data-circle" :class="bodyFatLevel">
              <div class="data-number">{{ bodyFatText }}</div>
              <div class="data-unit">%</div>
            </div>
            <div class="data-label" :class="bodyFatLevel">体脂率</div>
          </div>
        </div>
      </div>

      <!-- 功能菜单 -->
      <div class="menu-card" :class="{ 'loading': loading }">
        <div class="menu-item" v-for="(menu, index) in menuItems" :key="index" @click="handleMenuClick(menu)">
          <div class="menu-icon">
            <el-icon><component :is="menu.icon" /></el-icon>
          </div>
          <div class="menu-content">
            <div class="menu-title">{{ menu.title }}</div>
            <div class="menu-desc">{{ menu.desc }}</div>
          </div>
          <div class="menu-arrow">
            <el-icon><ArrowRight /></el-icon>
          </div>
        </div>
      </div>
      <el-button class="logout-btn" type="danger" @click="logout">
        退出登录
      </el-button>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-overlay">
        <el-loading-spinner />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  User,
  Camera,
  Edit,
  Calendar,
  Male,
  ArrowRight,
  Setting,
  Bell,
  Help,
  CreditCard,
  SwitchButton
} from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import request from '@/utils/request'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()
// 只在顶部调用一次 useUserStore
const userStore = useUserStore()
const loading = ref(true)
const profileData = reactive({
  id: null,
  user: null,
  user_phone: '',
  birthdate: '',
  weight: '',
  height: '',
  avatar_url: null,
  gender: ''
})

const editing = ref(false)
const saving = ref(false)
let backupProfile = null

// 计算BMI
const bmiValue = computed(() => {
  if (profileData.height && profileData.weight) {
    const heightInM = parseFloat(profileData.height) / 100
    const weightInKg = parseFloat(profileData.weight)
    const bmi = (weightInKg / (heightInM * heightInM)).toFixed(1)
    return bmi
  }
  return '--'
})

// 性别显示
const genderText = computed(() => {
  return profileData.gender === 'M' ? '男' : profileData.gender === 'F' ? '女' : '--'
})

// 年龄显示
const ageText = computed(() => {
  if (profileData.birthdate) {
    const birth = new Date(profileData.birthdate)
    const now = new Date()
    let age = now.getFullYear() - birth.getFullYear()
    const m = now.getMonth() - birth.getMonth()
    if (m < 0 || (m === 0 && now.getDate() < birth.getDate())) {
      age--
    }
    return age
  }
  return '--'
})

// 体脂率计算公式（成年男性/女性）
const bodyFatText = computed(() => {
  const weight = parseFloat(profileData.weight)
  const height = parseFloat(profileData.height)
  const gender = profileData.gender
  const age = ageText.value
  if (!weight || !height || !gender || !age || age === '--') return '--'
  // BMI
  const bmi = weight / Math.pow(height / 100, 2)
  // 体脂率公式（Deurenberg公式）
  // 男: 1=男, 女: 0=女
  const sex = (gender === 'M' || gender === '男') ? 1 : 0
  const fat = 1.2 * bmi + 0.23 * age - 5.4 - 10.8 * sex
  return fat.toFixed(1) + '%'
})

// 在身体数据卡片中绑定 class
const bmiLevel = computed(() => {
  const bmi = parseFloat(bmiValue.value)
  if (isNaN(bmi)) return 'normal'
  if (bmi < 18.5) return 'mild'         // 偏瘦
  if (bmi < 24) return 'normal'         // 正常
  if (bmi < 28) return 'mild'           // 超重
  if (bmi < 32) return 'moderate'       // 肥胖
  return 'severe'                       // 重度肥胖
})

const bodyFatLevel = computed(() => {
  let fat = bodyFatText.value
  if (typeof fat === 'string') fat = fat.replace(/[^0-9.]/g, '')
  fat = parseFloat(fat)
  const gender = profileData.gender
  if (isNaN(fat)) return 'normal'
  if (gender === 'M' || gender === '男') {
    if (fat < 10) return 'mild'
    if (fat <= 20) return 'normal'
    if (fat <= 25) return 'mild'
    if (fat <= 30) return 'moderate'
    return 'severe'
  } else if (gender === 'F' || gender === '女') {
    if (fat < 18) return 'mild'
    if (fat <= 28) return 'normal'
    if (fat <= 33) return 'mild'
    if (fat <= 38) return 'moderate'
    return 'severe'
  }
  return 'normal'
})

const heightLevel = computed(() => {
  const height = parseFloat(profileData.height)
  const gender = profileData.gender
  if (isNaN(height)) return 'normal'
  if (gender === 'M' || gender === '男') {
    if (height < 165) return 'mild'
    if (height <= 180) return 'normal'
    return 'mild'
  } else if (gender === 'F' || gender === '女') {
    if (height < 155) return 'mild'
    if (height <= 170) return 'normal'
    return 'mild'
  }
  return 'normal'
})

const weightLevel = computed(() => {
  const height = parseFloat(profileData.height)
  const weight = parseFloat(profileData.weight)
  if (isNaN(height) || isNaN(weight)) return 'normal'
  const heightM = height / 100
  const stdWeight = heightM * heightM * 22
  if (weight < stdWeight * 0.9) return 'mild'
  if (weight <= stdWeight * 1.1) return 'normal'
  if (weight <= stdWeight * 1.2) return 'moderate'
  return 'severe'
})

// 信息项配置
const infoItems = computed(() => [
  {
    label: '性别',
    value: genderText.value,
    icon: Male
  },
  {
    label: '生日',
    value: profileData.birthdate || '--',
    icon: Calendar
  },
  {
    label: '年龄',
    value: ageText.value,
    icon: Calendar
  },
  {
    label: '实名认证',
    value: userStore.isRealName ? '已实名' : '未实名',
    icon: CreditCard,
    action: userStore.isRealName ? null : () => router.push('/realname_auth')
  }
])

// 菜单项配置
const menuItems = [
  {
    title: '设置',
    desc: '账户设置与偏好',
    icon: Setting,
    action: 'settings'
  },
  {
    title: '通知',
    desc: '消息与提醒设置',
    icon: Bell,
    action: 'notifications'
  },
  {
    title: '帮助',
    desc: '常见问题与支持',
    icon: Help,
    action: 'help'
  },
  {
    title: '退出登录',
    desc: '',
    icon: SwitchButton,
    action: 'logout'
  }
]

// 处理菜单点击
const handleMenuClick = (menu) => {
  if (menu.action === 'logout') {
    logout()
  } else {
    ElMessage.info(`点击了${menu.title}`)
  }
}

// 保存个人信息
const saveProfile = async () => {
  saving.value = true
  try {
    const userid = userStore.userid
    // birthdate 格式化
    let formattedBirthdate = profileData.birthdate
    if (formattedBirthdate) {
        if (formattedBirthdate instanceof Date) {
          formattedBirthdate = formattedBirthdate.toISOString().slice(0, 10)
        } else if (typeof formattedBirthdate === 'string' && formattedBirthdate.includes('T')) {
          formattedBirthdate = formattedBirthdate.slice(0, 10)
        }
    }
    // 只提交需要修改的字段
    const payload = {
      gender: profileData.gender,
      birthdate: formattedBirthdate,
      height: profileData.height,
      weight: profileData.weight,
      // 可根据需要添加更多字段
    }
    const res = await request.patch(`/user/profiles/${userid}/`, payload)
    if (res) {
      Object.assign(profileData, res)
    }
    editing.value = false
    ElMessage.success('保存成功')
  } catch (error) {
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

// 取消编辑
const cancelEdit = () => {
  editing.value = false
  // 恢复备份数据
  if (backupProfile) {
    Object.assign(profileData, backupProfile)
  }
}

const isGuest = computed(() => {
  return profileData.id === 'guest' || !userStore.isLoggedIn
})

const pollingTimer = ref(null)
const hasShownRealnameSuccess = ref(false)

const fetchUserProfile = async () => {
  try {
    const userid = userStore.userid
    console.log("前端请求的userid",userid)
    if (!userid) return
    const res = await request.get(`/user/profiles/${userid}/`)
    if (res && (res.is_realname === true || res.is_realname === 1 || res.is_realname === '1')) {
      userStore.isRealName = true
    } else {
      userStore.isRealName = false
    }
    if (res) {
      Object.assign(profileData, res)
    }
  } catch (e) {
    // 可选：处理请求异常
  } finally {
    loading.value = false
  }
}

const myStats = reactive({
  posts: 0,
  favorites: 0,
  likes: 0,
  fans: 0,
  follows: 0
})

// 新增：获取用户统计信息
async function fetchUserStats() {
  try {
    const userid = userStore.userid
    if (!userid) return
    // 假设后端有 /user/profiles/{userid}/stats/ 接口，若无可用 /user/profiles/{userid}/
    let res = await request.get(`/user/profiles/${userid}/stats/`)
    // 如果没有 stats 接口，尝试直接从 profile 里取
    if (!res || typeof res !== 'object' || res.code === 404) {
      res = await request.get(`/user/profiles/${userid}/`)
    }
    // 兼容不同返回结构
    const stats = res.data || res
    myStats.posts = stats.posts ?? 0
    myStats.favorites = stats.favorites ?? 0
    myStats.likes = stats.likes ?? 0
    myStats.fans = stats.fans ?? 0
    myStats.follows = stats.follows ?? 0
  } catch (e) {
    // 可选：错误处理
  }
}

onMounted(() => {
  // 优先从 localStorage 读取 userid
  let uid = userStore.userid || localStorage.getItem('userid')
  if (uid) {
    userStore.setUserid(uid) // 用方法赋值，避免只读错误
    fetchUserProfile()
    fetchUserStats() // 新增：获取统计信息
  } else {
    loading.value = false // 没有uid时也要关闭loading，防止页面卡住
  }
})

// watch(() => userStore.isRealName, (val) => {
//   if (val && pollingTimer.value && !hasShownRealnameSuccess.value) {
//     ElMessage.success('实名认证成功！')
//     hasShownRealnameSuccess.value = true
//     clearInterval(pollingTimer.value)
//     pollingTimer.value = null
//     // 跳转去掉参数，防止刷新重复弹
//     router.replace({ path: '/user' })
//     // 自动刷新页面，确保所有数据都是最新的
//     setTimeout(() => {
//       window.location.reload()
//     }, 500) // 延迟0.5秒，确保路由参数已去除
//   }
// })

// onUnmounted(() => {
//   if (pollingTimer.value) clearInterval(pollingTimer.value)
// })

const logout = () => {
  userStore.clearUserInfo()
  localStorage.removeItem('token')
  router.replace({ path: '/' })
}

watch(
  () => userStore.userid,
  (newVal) => {
    if (newVal) {
      fetchUserProfile()
    }
  },
  { immediate: true }
)
</script>

<style scoped>
.user-bg {
  min-height: 100vh;
  width: 100vw;
  /* background: url('/future.png') center center/cover no-repeat fixed; */
}

.profile-container {
  padding: 16px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.profile-header {
  background: linear-gradient(90deg, #e0e7ef 0%, #fff 100%);
  border-radius: 16px;
  padding: 32px 24px 24px 24px;
  margin-bottom: 16px;
  box-shadow: 0 2px 12px 0 rgba(44,62,80,0.08);
  display: flex;
  align-items: center;
  gap: 18px;
}

.avatar-section {
  display: flex;
  align-items: center;
  gap: 18px;
}

.avatar-wrapper {
  position: relative;
}

.avatar {
  border: 3px solid #f0f0f0;
  box-shadow: 0 2px 8px #e0e7ef;
}

.avatar-edit {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 28px;
  height: 28px;
  background: #409eff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  cursor: pointer;
  box-shadow: 0 2px 8px #409eff44;
}

.user-info {
  flex: 1;
}

.username {
  margin: 0 0 4px 0;
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.user-id {
  margin: 0 0 4px 0;
  font-size: 14px;
  color: #888;
}

.login-type {
  margin: 0;
  font-size: 12px;
  color: #409eff;
  background: #ecf5ff;
  padding: 2px 8px;
  border-radius: 10px;
  display: inline-block;
}

.profile-card {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 12px 0 rgba(44,62,80,0.08);
  padding: 20px 0 10px 0;
  margin-bottom: 18px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.info-grid {
  display: flex;
  flex-wrap: wrap;
  border-top: 1px solid #f0f0f0;
}

.info-item {
  flex: 1 1 50%;
  padding: 12px 0 12px 24px;
  border-bottom: 1px solid #f0f0f0;
  border-right: 1px solid #f0f0f0;
  min-width: 180px;
  background: transparent;
  transition: background 0.2s;
}

.info-item:last-child, .info-item:nth-child(2n) {
  border-right: none;
}

.info-item:hover {
  background: #f8fafc;
}

.info-label {
  font-size: 14px;
  color: #888;
  margin-bottom: 2px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.info-value {
  font-size: 17px;
  font-weight: 600;
  color: #222;
}

.info-value.link {
  color: #409eff;
  cursor: pointer;
}

.info-value.link:hover {
  text-decoration: underline;
}

.body-data-card {
  background: linear-gradient(120deg, #f8fafc 0%, #e0e7ef 100%);
  border-radius: 18px;
  box-shadow: 0 4px 24px 0 rgba(44,62,80,0.10);
  padding: 24px 0 18px 0;
  margin-bottom: 18px;
  margin-top: 18px;
}

.data-grid {
  display: flex;
  justify-content: space-around;
  align-items: flex-start;
  margin-top: 12px;
}

.data-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.data-circle {
  width: 70px;
  height: 70px;
  border-radius: 50%;
  background: linear-gradient(135deg, #fff 60%, #e0e7ef 100%);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 0 auto 6px auto;
  box-shadow: 0 2px 8px 0 rgba(44,62,80,0.06);
  font-size: 22px;
  font-weight: 700;
  color: #222;
  position: relative;
  transition: box-shadow 0.2s;
}

.data-item .data-label {
  text-align: center;
  font-size: 14px;
  color: #888;
  margin-top: 2px;
}

/*
.data-item:last-child .data-circle {
  background: linear-gradient(135deg, #ffe0e0 60%, #ffd6d6 100%);
  color: #e74c3c;
}
.data-item:last-child .data-label {
  color: #e74c3c;
  font-weight: 600;
}
*/

.data-circle .data-number,
.data-circle .data-unit {
  color: #fff;
  text-shadow: 0 2px 8px #0005, 0 0px 2px #fff8;
}
.data-circle.normal {
  background: linear-gradient(135deg, #a5d6a7 40%, #388e3c 100%);
}
.data-circle.mild {
  background: linear-gradient(135deg, #ffe082 40%, #ffb300 100%);
}
.data-circle.moderate {
  background: linear-gradient(135deg, #ffb74d 40%, #f57c00 100%);
}
.data-circle.severe {
  background: linear-gradient(135deg, #ef9a9a 40%, #c62828 100%);
}

.data-number {
  font-size: 18px;
  font-weight: 600;
  line-height: 1;
}

.data-unit {
  font-size: 12px;
  opacity: 0.8;
}

.menu-card {
  background: #fff;
  border-radius: 16px;
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: 0 2px 12px 0 rgba(44,62,80,0.08);
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.3s;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-item:hover {
  background: #f8f9fa;
  border-radius: 8px;
  padding-left: 12px;
  padding-right: 12px;
  margin: 0 -12px;
}

.menu-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  background: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  color: #666;
}

.menu-content {
  flex: 1;
}

.menu-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 2px;
}

.menu-desc {
  font-size: 12px;
  color: #888;
}

.menu-arrow {
  color: #ccc;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.loading {
  filter: blur(4px);
  pointer-events: none;
}

.logout-btn {
  width: 90%;
  margin: 32px auto 0 auto;
  display: block;
  font-size: 18px;
  font-weight: 600;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(255, 99, 71, 0.08);
  background: linear-gradient(90deg, #ff6b6b 0%, #ff8787 100%);
  color: #fff;
  border: none;
  transition: background 0.2s, box-shadow 0.2s;
  letter-spacing: 2px;
}
.logout-btn:hover {
  background: linear-gradient(90deg, #ff8787 0%, #ff6b6b 100%);
  box-shadow: 0 4px 16px rgba(255, 99, 71, 0.16);
  filter: brightness(1.05);
}

.user-quick-stats {
  display: flex;
  justify-content: space-around;
  align-items: center;
  background: #fff;
  border-radius: 16px;
  margin-bottom: 18px;
  padding: 18px 0 10px 0;
  box-shadow: 0 2px 12px 0 rgba(44,62,80,0.06);
}
.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 48px;
}
.stat-value {
  font-size: 20px;
  font-weight: 700;
  color: #222;
  margin-bottom: 2px;
}
.stat-label {
  font-size: 13px;
  color: #888;
}

.logout-menu .menu-title {
  color: #ff4d4f;
  font-weight: 700;
}

.data-circle.normal {
  background: linear-gradient(135deg, #e8f5e9 60%, #4caf50 100%);
  color: #fff;
}
.data-label.normal {
  color: #388e3c;
  font-weight: 700;
}
.data-circle.mild {
  background: linear-gradient(135deg, #fffde7 60%, #ffd600 100%);
  color: #fff;
}

.data-label.mild {
  color: #ffb300;
  font-weight: 700;
}
.data-circle.moderate {
  background: linear-gradient(135deg, #fff3e0 60%, #ff9800 100%);
  color: #fff;
}

.data-label.moderate {
  color: #f57c00;
  font-weight: 700;
}
.data-circle.severe {
  background: linear-gradient(135deg, #ffebee 60%, #f44336 100%);
  color: #fff;
}
.data-label.severe {
  color: #c62828;
  font-weight: 700;
}
</style>